const CONTEXT = require('../../utils/public_var.js')
function getPromoteList(list) {

  let slicedItems = null
  slicedItems = list.slice(list.length - 1, list.length);
  return slicedItems
}
module.exports = {
  async startOCR(that,session){
    var con = that
    if (con.data.ocr.faceImgUrl) {
      const canvas = wx.createOffscreenCanvas({
          type: '2d',
          width: con.data.ocr.faceImgOriginWidth,
          height: con.data.ocr.faceImgOriginHeight,
      })
      const context = canvas.getContext('2d')
      const img = canvas.createImage()
      await new Promise(resolve => {
          img.onload = resolve
          img.src = con.data.ocr.faceImgUrl
      })
  
      context.clearRect(0, 0, con.data.ocr.faceImgOriginWidth, con.data.ocr.faceImgOriginHeight)
      context.drawImage(img, 0, 0, con.data.ocr.faceImgOriginWidth, con.data.ocr.faceImgOriginHeight)
  
     var imageData = context.getImageData(0, 0, con.data.ocr.faceImgOriginWidth, con.data.ocr.faceImgOriginHeight)
  
      session.start(errno => {
        if (errno) {
          console.log(errno)
          // 如果失败，将返回 errno
        } else {
          console.log("runOCR")
          // 否则，返回null，表示成功
          session.runOCR({
            frameBuffer: imageData.data.buffer,
            width: con.data.ocr.faceImgOriginWidth,
            height: con.data.ocr.faceImgOriginHeight,
          })
        }
      })
      
  }
  },
  shibiewenzi(that,app,session){
    console.log(session)
    var con  = that
    if (app.globalData.OpenID == "" || app.globalData.OpenID == undefined) {
      wx.showModal({
        title: '',
        content: '请您登录验证',
        confirmText: '登录',
        complete: (res) => {
          if (res.cancel) {
  
          }
          if (res.confirm) {
            wx.redirectTo({
              url: '/pages/login/atLogin/atLogin',
            })
          }
        }
      })
      return
    }

    if (con.data.totalCount > 0) {

        wx.chooseMedia({
          count: 1,
          sizeType: ['compressed'],
          mediaType: ['image'],
          sourceType: ['album', 'camera'],
          success(res){
            var imgs = res.tempFiles;
            var imgUrl = imgs[0].tempFilePath
            console.log(imgUrl)
            con.hintAll()

            var imgs = res.tempFiles;
            
            con.addUpImg(imgs[0].tempFilePath);
      
              wx.getImageInfo({
                src: imgUrl,
                success: res => {
                    const fixWidth = 300
                    const {
                        width,
                        height
                    } = res
                    console.log(con)
                    con.setData({
                      ocr:{
                        faceImgUrl: imgUrl,
                        faceImgWidth: fixWidth,
                        faceImgHeight: (fixWidth / width) * height,
                        faceImgOriginWidth: width,
                        faceImgOriginHeight: height
                    }
                    })
                   
                    module.exports.startOCR(con,session)
                },
                fail: res => {
                    console.error(res)
                }
            })
          
          },fail(res){
            console.log(res)
          }
        })
  }else{
     // 没有免费使用次数了
     wx.showModal({
      title: '体验用尽',
      content: '在下养家糊口，\n恳请主公雇佣在下',
      confirmText: "雇佣",
      cancelText: "取消",
      complete: (res) => {
        if (res.cancel) {}
        if (res.confirm) {
          wx.navigateTo({
            url: '/pages/sita/pay/paybill',
          })
        }
      }
    })
   
  }
  },
  setORCText(app,that,text,imguri,requestUrl){
   
    if(that.data.input_tx ==""){
      wx.showToast({
        title: '请告诉我能帮您做什么',
        icon: "none"
      })
      return
    }
  
    var con = that
    var data = {
    "role": 'user',
    "content": that.data.input_tx,
    "upImgUrl":imguri,
    "msgtype":CONTEXT.TEXT
    }
    var list = con.data.MessageList
    list.push(data)
    con.setData({
      MessageList: list
    })
    con.setData({
      intoViewName: 'endview',
    })
    wx.showLoading({
      title: "主公请稍后，我在构思中"
    })
    wx.request({
      url: requestUrl,
      header: {
        'content-type': 'application/json',
      },
      method: 'POST',
      data: {
        "prompt": [{
         
            "role": 'user',
            "content": that.data.input_tx,
            "msgtype":CONTEXT.TEXT
            },
            {
         
              "role": 'user',
              "content": text,
              "msgtype":CONTEXT.TEXT
              }
        ],
        'openid': app.globalData.OpenID
      },
      success(res) {
        wx.hideLoading()
        console.log(res.data)
        if (res.data.statusCode == 200) {
          var sys_message = {
            "role": "system",
            "content": res.data.completeOpenAnswer.gptAnswer,
            "msgtype": CONTEXT.TEXT

          }
          list.push(sys_message)
          that.setData({
            MessageList: list,
            input_tx: "",
            totalCount: res.data.completeOpenAnswer.remainingGPTCount,
          })
          app.setCount(res.data.completeOpenAnswer.remainingGPTCount)
          app.saveMsg(con.data.bar_type,list)

            that.setData({
              intoViewName: 'endview'
            })
         
   
       

         
          con.initSendUI();

         
        } else {

        }


      },
      fail(res) {
        wx.hideLoading()
        console.log(res)
      }
    })
    

  }

}
